package com.zymail.controller;

import com.zymail.bean.ZyFloor;
import com.zymail.bean.ZyUser;
import com.zymail.service.ZyFloorService;
import com.zymail.service.ZyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/floor")
public class FloorController extends BaseController{

    @Autowired
    public ZyFloorService floorService;

    @Autowired
    public ZyUserService userService;

    /**
     * 得到个人的所有地址
     * @param session_key session_key
     * @return List<ZyFloor>
     */
    @RequestMapping("/getfloors/{session_key}")
    public List<ZyFloor> getmyfloors(@PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;
        return floorService.getmyfloors(userId);
    }

    /**
     * 删除某个地址
     * @param id 用户id
     * @return  boolean
     */
    @DeleteMapping("/delfloor/{id}")
    public boolean delfloor(@PathVariable("id") Integer id){
        ZyFloor floor = floorService.getById(id);
        floor.setMajor(0);
        return floorService.updateById(floor);
    }

    /**
     * 修改地址
     * @param floor 修改的实体
     * @return  boolean
     */
    @PutMapping("/editfloor/{session_key}")
    public boolean editfloor(@RequestBody ZyFloor floor, @PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return false;

        ZyUser user = userService.getById(userId);

        Integer oldId = floor.getId();
        ZyFloor old =  floorService.getById(oldId);
        old.setMajor(0);
        floorService.updateById(old);


        floor.setId(null);
        floor.setUserId(userId);
        floor.setMajor(1);
        boolean flag = floorService.save(floor);

        if(!flag) return false;
        if(user.getDefFloor().equals(oldId)){
            user.setDefFloor(floor.getId());
            return userService.updateById(user);
        }

        return true;
    }

    /**
     * 添加地址
     * @param floor 添加的实体
     * @return ZyFloor
     */
    @PostMapping("/addfloor/{session_key}")
    public ZyFloor addfloor(@RequestBody ZyFloor floor, @PathVariable("session_key") String session_key){
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;

        floor.setUserId(userId);
        floor.setMajor(1);

        if (floorService.save(floor)){
            return floor;
        }
        return null;
    }

}
